package com.dzsw.simple.server.controller;


import com.dzsw.simple.server.util.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.net.URL;

@RestController
@RequestMapping("/images")
public class ImagesController {

    private static final String BASE_PATH = ImagesController.class.getResource("/").getPath();

    @GetMapping("/{p1}")
    public void images(@PathVariable String p1, HttpServletResponse response) throws Exception {
        URL url = this.getClass().getClassLoader().getResource("images/" + p1);
        if (url != null) {
            try (var bis = new BufferedInputStream(new FileInputStream(url.getPath().substring(1)));
                 var out = response.getOutputStream()) {
                response.setContentType(FileUtil.getContentType(bis));
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = bis.read(buff)) > 0) {
                    out.write(buff, 0, len);
                }
                out.flush();
            }
        }
    }
}
